package com.school.graduation.detailed.presenter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import com.school.graduation.detailed.model.DetailedAdapter;
import com.school.graduation.detailed.model.DetailedModelNew;
import com.school.graduation.detailed.view.DetailedActivityNew;
import com.school.graduation.model.Detailed;
import com.school.graduation.util.ToastUtil;
import com.school.graduation.view.SignInActivity;

import static android.content.Context.MODE_PRIVATE;


public class DetailedPresenterNew {
    private DetailedActivityNew view;
    private DetailedModelNew model;
    private Context context;
    private DetailedAdapter adapter;
    public DetailedPresenterNew(Context context, DetailedActivityNew view){
        this.context = context;
        this.view = view;
        model = new DetailedModelNew(context,this);
    }

    public void getDetailed(String id){
        initAdapter(id);
    }

    private void initAdapter(String id){
        try{
            adapter = new DetailedAdapter(context, getUserId());
            view.initAdapter(adapter);
            model.getDetailed(id);
        }catch (NullPointerException e){
            Intent intent = new Intent(context, SignInActivity.class);
            context.startActivity(intent);
            view.finish();
        }
    }

    public void initContent(Detailed detailed){
        if (detailed.getProduct() == null){
            ToastUtil.makeShortToast(context,"这件商品已经被买走了，看看其他的吧");
            view.finish();
        }else {
            view.initImage(detailed.getProduct().getImg());
            view.initContent(detailed);
            adapter.initData(detailed.getComments());
        }

    }

    public void upData(Detailed detailed){
        adapter.initData(detailed.getComments());
    }

    private String getUserId(){
        SharedPreferences preferences = context.getSharedPreferences("user_cache",MODE_PRIVATE);
        String userId = preferences.getString("id","");
        return userId;
    }
}
